package cn.cjj.gulimall.auth.web;

import cn.cjj.common.constant.AuthServerConstant;
import cn.cjj.common.exception.BizCodeEnume;
import cn.cjj.common.utils.R;
import cn.cjj.common.vo.MemberResponseVo;
import cn.cjj.gulimall.auth.feign.MemberFeignService;
import cn.cjj.gulimall.auth.feign.SmsFeignService;
import cn.cjj.gulimall.auth.vo.UserLoginVo;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


/**
 * @author CuiJunJie
 * @create 2021/7/1-17:02
 */
@Slf4j
@Controller
public class LoginController {

    @Value("${module.name}")
    private String moduleName;

    @Autowired
    MemberFeignService memberFeignService;


    @RequestMapping("/login")
    public String login(UserLoginVo user, RedirectAttributes redirectAttributes, HttpSession session) {
        R r = memberFeignService.login(user);
        if (r.getCode() == 0) {
            log.info("登录成功");
            Object data = r.get("data");
            String memberJsonString = JSON.toJSONString(data);
            MemberResponseVo member = JSON.parseObject(memberJsonString, MemberResponseVo.class);
            System.out.println(member);
            session.setAttribute(AuthServerConstant.LOGIN_USER, member);
            return "redirect:http://gulimall.com";
        } else {
            HashMap<String, String> errors = new HashMap<>();
            errors.put("msg", r.getMsg());
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }

    @ResponseBody
    @RequestMapping("/module/name")
    public String moduleName() {
        return moduleName;
    }

    @GetMapping({"/login.html"})
    public String toLoginPage() {
        return "login";
    }
}
